<?php
namespace App\Presenters;

use App\Models\AdminRole;
use App\Repositories\AdminMenuRepository;
use Route;

/**
*  加载菜单
*/
class MenusPresenter
{
    protected $Repo;
    function __construct(AdminMenuRepository $repo)
    {
        $this->Repo = $repo;
    }

    //不同角色可见菜单
    public function initMenus()
    {
        $allMenus = $this->Repo->getAllMenus(true);
        // dump($allMenus);
        $html = '';

        $adminMenus = $this->adminMenus();
        // dump($adminMenus);
        $adminUser = session('admin');

        foreach ($allMenus as $menu) {
            if ($menu['route'] != '#' && !Route::has($menu['route'])) continue;
            if ($adminUser->is_super || in_array($menu['id'], $adminMenus)) {
                $html .= '<li class="layui-nav-item">';
                $href  = ($menu['route'] == '#') ? '#' : route($menu['route']);
                $html .= '<a href="'.$href.'"><i class="layui-icon">'.$menu['icon'].'</i>'.$menu['title'].'</a>';

                if (!isset($menu['sub'])) {
                    $html .= '</li>';
                    continue;
                }

                $html .= '<dl class="layui-nav-child">';

                foreach ($menu['sub'] as $sub) {
                    if ($menu['route'] != '#' && !Route::has($sub['route'])) continue;
                    if ($adminUser->is_super || in_array($sub['id'], $adminMenus)) {
                        $href = ($sub['route'] == '#') ? '#' : route($sub['route']);
                        $html .= '<dd><a href="'.$href.'"><i class="layui-icon">'.$sub['icon'].'</i>'.$sub['title'].'</a></dd>';
                    }

                }
                $html .= '</dl></li>';

            }
        }

        return $html;
    }

    //获取当前用户菜单id
    public function adminMenus()
    {
        $adminUser = session('admin');
        $roles = $adminUser->roles()->get();

        $adminMenus = [];
        foreach ($roles as $value) {
            foreach (AdminRole::find($value->id)->menus()->where('is_menu', 1)->get() as $val) {
                $adminMenus[] = $val->id;
            }
        }
        return array_unique($adminMenus);
    }
}